package com.liuyi.netty.im.test.im.client;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author Mr.Fmy
 * @since 2022/1/19
 */
public class ChannelStorage {

    private static final ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final AttributeKey<Boolean> readyKey = AttributeKey.valueOf("readyKey");
    private static final AttributeKey<String> userKey = AttributeKey.valueOf("userKey");

    public static int size() {
        return group.size();
    }

    public static int readySize() {
        return (int) group.stream().filter(c -> {
            Attribute<Boolean> b = c.attr(readyKey);
            if (b != null) {
                return b.get() != null && b.get();
            }
            return false;
        }).count();
    }

    public static void add(Channel channel) {
        group.add(channel);
    }

    public static void remove(Channel channel) {
        group.remove(channel);
    }

    public static void ready(ChannelId channelId) {
        Channel channel = group.find(channelId);
        if (channel != null) {
            channel.attr(readyKey).set(true);
        }
    }

    public static boolean getReady(ChannelId channelId) {
        Channel channel = group.find(channelId);
        if (channel != null) {
            Attribute<Boolean> b = channel.attr(readyKey);
            if (b != null) {
                return b.get() != null && b.get();
            }
        }
        return false;
    }

    public static void notReady(ChannelId channelId) {
        Channel channel = group.find(channelId);
        if (channel != null) {
            channel.attr(readyKey).set(false);
        }
    }

    public static void userInfo(ChannelId channelId, String userId) {
        Channel channel = group.find(channelId);
        if (channel != null) {
            channel.attr(userKey).set(userId);
        }
    }

    public static String getUserInfo(ChannelId channelId) {
        Channel channel = group.find(channelId);
        if (channel != null) {
            Attribute<String> attr = channel.attr(userKey);
            if (attr != null){
                return attr.get();
            }
        }
        return null;
    }
}
